/*
 * Copyright (C) 2004, Velocityme Partnership
 * AttachmentAction.java
 *
 * Created on 03 January 2005, 08:53
 */

package com.velocityme.www.interfaces;

import com.velocityme.entity.FileAttachment;
import com.velocityme.session.FileAttachmentLocal;
import com.velocityme.session.KeyLocal;
import com.velocityme.www.actionforms.AttachmentActionForm;
import java.io.BufferedInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author  Robert
 */
public class AttachmentAction extends org.apache.struts.action.Action {
    
    /** Creates a new instance of AttachmentAction */
    public AttachmentAction() {
    }
    
    @Override
    public ActionForward execute(ActionMapping mapping, 
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        AttachmentActionForm attachment = (AttachmentActionForm)form;
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        FileAttachmentLocal fileAttachmentLocal = lookupFileAttachmentBean();
        FileAttachment fileAttachment = fileAttachmentLocal.findFileAttachment(key, attachment.getName());
        BufferedInputStream bis = fileAttachmentLocal.getFileAttachmentInputStream(key, fileAttachment);
	response.reset();
	response.setContentType(fileAttachment.getContentType());
	response.setHeader("Content-Disposition","attachment; filename=\"" +fileAttachment.getName()+ "\";");
        response.setContentLength((int)fileAttachmentLocal.getFileAttachmentLength(key, fileAttachment));
        ServletOutputStream bos = response.getOutputStream();
        byte [] buffer = new byte[bis.available()];
        int bytesRead = 0;
        while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bis.close();
        bos.flush();
        bos.close();
        return null;
    }

    private FileAttachmentLocal lookupFileAttachmentBean() {
        try {
            Context c = new InitialContext();
            return (FileAttachmentLocal) c.lookup("java:comp/env/FileAttachmentBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    
}
